from flask import render_template,redirect,request,url_for,flash
from flask_login import login_user,logout_user,login_required
from . import auth
from ..models import User
from .forms import LoginForm,RegistrationForm,ChangePasswordForm,PasswordResetForm,ResetForm
from .. import db
from ..email import mySendMail
from flask_login import current_user



#登入用户
@auth.route('/login',methods=['GET','POST'])
def login():
	form=LoginForm()
	if form.validate_on_submit():
		user=User.query.filter_by(email=form.email.data).first()
		if user is not None and user.verify_password(form.password.data):
			login_user(user,form.remember_me.data)
			return redirect(request.args.get('next') or url_for('main.index'))
		flash('Invalid user name or password')
	return render_template('auth/login.html',form=form)


#登出用户
@auth.route('/logout')
@login_required
def logout():
	logout_user()
	flash('You have been logged out.')
	return redirect(url_for('main.index'))



#用户注册路由
#发送确认邮件
@auth.route('/register',methods=['GET','POST'])
def register():
	form=RegistrationForm()
	if form.validate_on_submit():
		user=User(email=form.email.data,
			username=form.username.data,
			password=form.password.data) 
		db.session.add(user)
		db.session.commit()
		token=user.generate_confirmation_token()
		content=url_for('auth.confirm',token=token,_external=True)
		subject="激活账户"
		# mySendMail(receivers,content,sender_name,receivers_name,title)
		mySendMail(user.email,content,subject)
		# send_email(user.email,'Comfirm Your Account','auth/email/confirm',user=user,token=token)
		flash('A confirmation email has been sent to you by email.')
		return redirect(url_for('main.index'))
	return render_template('auth/register.html',form=form)

#确认用户的账户
@auth.route('/confirm/<token>')
@login_required
def confirm(token):
	if current_user.confirmed:
		return redirect(url_for('main.index'))
	if current_user.confirm(token):
		flash('You have confirmed your account.Thanks')
	else:
		flash('The confirmation link is invalid or has expired.')
	return redirect(url_for('main.index'))

# #在before_app_request处理程序中过滤未确认的账户
# @auth.before_app_request
# def before_request():
# 	if current_user.is_authenticated \
# 			and not current_user.confirmed \
# 			and request.endpoint[:5]!='auth.' \
# 			and request.endpoint!='static':
# 		return redirect(url_for('auth.unconfirmed'))

# @auth.route('/unconfirmed')
# def unconfirmed():
# 	if current_user.is_anonymous or current_user.confirmed:
# 		return redirect(url_for('main.index'))
# 	return render_template('auth/unconfirmed.html')

# #重新发送用户确认邮件
# @auth.route('/confirm')
# @login_required
# def resend_confirmation():
# 	token=current_user.generate_confirmation_token()
# 	send_email(current_user.email,'Comfirm Your Account','auth/email/confirm',user=current_user,token=token)
# 	flash('A new confirmation email has been send to you by email.')
# 	return redirect(url_for('main.index'))

#修改密码
@auth.route('/change_password',methods=['GET','POST'])
@login_required
def change_password():
    form=ChangePasswordForm()
    if form.validate_on_submit():
        #验证输入的旧密码是否正确
        if current_user.verify_password(form.old_password.data ):
            current_user.password=form.password.data
            db.session.add(current_user)
            db.session.commit()
            token=current_user.generate_confirmation_token()
            content=url_for('auth.confirm',token=token,_external=True)
            subject="修改密码"
            mySendMail(current_user.email,content,subject)
            flash('A confirmation email has been sent to you by email.')
            return redirect(url_for('auth.login'))
        else:
            flash("Invalid password")
    return render_template('auth/change_password.html',form=form)

#发送重置密码邮件
@auth.route('/password_reset_request',methods=('GET','POST'))
def password_reset_request():
    form=PasswordResetForm()
    if form.validate_on_submit():
        user=User.query.filter_by(email=form.email.data).first()
        if user:
        	# 发送带有重置密码连接的邮件
            token=user.generate_confirmation_token()
            content=url_for('auth.reset',token=token,_external=True)
            subject="重置密码"
            mySendMail(form.email.data,content,subject)
            flash('一封重置密码邮件已发送到您的邮箱，请查收')    
        else:
            flash("邮箱尚未注册")
    return render_template('auth/resetpassword.html',form=form)

#重置密码
@auth.route('/reset/<token>',methods=['GET','POST'])
def reset(token):
	form=ResetForm()
	if form.validate_on_submit():
		 user=User.query.filter_by(email=form.email.data).first()
		 user.password=form.password.data
		 db.session.add(user)
		 db.session.commit()
		 # print(11111111111111)
		 flash('你的密码已经更改，请重新登陆')
		 return redirect(url_for('auth.login'))
	return render_template('auth/reset.html',form=form)
